﻿using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using XFABManager;

namespace XFGameFramework.BuffSystem
{

    [CustomEditor(typeof(BuffConfigData), true)]
    public class BuffConfigDataInspector : Editor
    {

        private static BuffConfigDataInspector _instance;

        public static BuffConfigDataInspector Instance
        {
            get
            {
                if (_instance == null)
                    _instance = CreateInstance<BuffConfigDataInspector>();
                return _instance;
            }
        }

        private BuffConfigData currentBuffConfigData;

        private SerializedObject currentSerializedObject;

        private List<SerializedProperty> currentSerializeProperty;

        private Vector2 currentPosition;
         
        private SerializedProperty script = null;
          
        public override void OnInspectorGUI()
        {
            EditorGUI.BeginDisabledGroup(true);

            base.OnInspectorGUI();

            EditorGUI.EndDisabledGroup();

            //if (GUILayout.Button("编辑Buff"))
            //{
            //    BuffConfigsWindow window = EditorWindow.GetWindow<BuffConfigsWindow>();
            //    window.Show();
               

            //    BuffsConfig current = null;

            //    foreach (var item in BuffsConfigController.GetAllConfigs())
            //    {
            //        foreach (var buff in item.buffs)
            //        {
            //            if (buff == target)
            //            {
            //                current = item;
            //                break;
            //            }
            //        }
            //        if (current != null)
            //            break;
            //    }


            //    BuffConfigData currentBuff = target as BuffConfigData;
            //    string asset_path = AssetDatabase.GetAssetPath(current);
            //    BuffConfigsWindow.SelectGUID = AssetDatabase.AssetPathToGUID(asset_path);
            //    //window.RefreshCurrentBuffConfig(currentBuff.buff_id);
            //    window.SetSelection(currentBuff.buff_id);
            //    //BuffConfigsWindow.DefaultSelectBuffId = currentBuff.buff_id;
            //}
        }

        internal void OnInspectorGUI(BuffConfigData data, BuffConfigsWindow window, BuffsConfig currentBuffConfig)
        { 

            if (data != null)
            {
                if (currentBuffConfigData != data)
                {
                    currentBuffConfigData = data;
                    currentSerializedObject = null; 
                    script = null; 
                }

                if (currentSerializedObject == null)
                {
                    currentSerializedObject = new SerializedObject(currentBuffConfigData);
                    currentSerializeProperty = currentSerializedObject.GetAllSerializedProperty();
                }

                if (script == null)
                    script = currentSerializedObject.FindProperty("m_Script");

                currentSerializedObject.Update();

                currentPosition = GUILayout.BeginScrollView(currentPosition);

                EditorGUI.BeginDisabledGroup(true);
                //EditorGUILayout.LabelField(string.Empty, "类型", "BoldLabel");
                EditorGUILayout.PropertyField(script);
                EditorGUI.EndDisabledGroup();
                 
                for (int i = 0; i < currentSerializeProperty.Count; i++)
                { 

                    SerializedProperty property = currentSerializeProperty[i];

                    if (property.name == "parent" && property.objectReferenceValue == null) {
                        property.objectReferenceValue = currentBuffConfig;
                    }

                    if (GetPropertyCustomAttribute<HideInInspector>(property) != null) continue;
                    CustomPropertyGUI customPropertyGUI = GetPropertyCustomAttribute<CustomPropertyGUI>(property);
                    EditorGUI.BeginChangeCheck();

                    if (customPropertyGUI != null)
                    {
                        customPropertyGUI.OnPropertyGUI(property);
                    }
                    else
                    {
                        EditorGUILayout.PropertyField(property);
                    }

                    if (EditorGUI.EndChangeCheck())
                    {
                        currentSerializedObject.ApplyModifiedProperties();

                        if (property.name == "buff_id")
                            window.SetSelection(property.intValue);

                        if(currentBuffConfigData.parent != null)
                            currentBuffConfigData.parent.ClearCache();
                        
                        if (customPropertyGUI != null && customPropertyGUI.reloadTreeViewOnValueChange)
                            window.buffListTree.Reload();
                    }
                }

                GUILayout.EndScrollView();

                currentSerializedObject.ApplyModifiedProperties();
            }
            else
            {
                GUILayout.FlexibleSpace();
                EditorGUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                GUILayout.Label(string.Format("未查询到Buff,id:{0}!", window.currentShowBuffId));
                GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();
                GUILayout.FlexibleSpace();
            }
        }

         
        internal static Texture2D GetImage(string projectName, string assetName)
        {

            if (string.IsNullOrEmpty(projectName) || string.IsNullOrEmpty(assetName))
                return null;

            XFABProject project = XFABProjectManager.Instance.GetProject(projectName);

            if (project != null)
            {
                List<XFABAssetBundle> bundles = project.GetAllAssetBundles();

                foreach (var bundle in bundles)
                {
                    if (bundle == null)
                    {
                        continue;
                    }
                    string asset_path = bundle.GetAssetPathByFileName(assetName, typeof(Texture2D));

                    if (string.IsNullOrEmpty(asset_path))
                        asset_path = bundle.GetAssetPathByFileName(assetName, typeof(Sprite));

                    if (string.IsNullOrEmpty(asset_path))
                        continue;
                    Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(asset_path);
                    if (texture != null)
                        return texture;
                }
            }

            return null;
        }
          
        private Dictionary<SerializedProperty, Dictionary<Type, Attribute>> attributes = new Dictionary<SerializedProperty, Dictionary<Type, Attribute>>();

        private T GetPropertyCustomAttribute<T>(SerializedProperty property) where T : Attribute
        {
            if (!attributes.ContainsKey(property))
                attributes.Add(property, new Dictionary<Type, Attribute>());

            if (attributes[property].ContainsKey(typeof(T)))
                return attributes[property][typeof(T)] as T;

            Type type = property.serializedObject.targetObject.GetType();
            FieldInfo fieldInfo = type.GetField(property.name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            T customPropertyGUI = fieldInfo.GetCustomAttribute<T>();

            attributes[property].Add(typeof(T), customPropertyGUI);
            return customPropertyGUI;
        }

    }

}

